#!/bin/bash

# 处理 HOME 变量没有被设置的情况
if [ -z $HOME ]; then
    if [ "${CUSER}" = "root" ]; then
        HOME="/root"
    else
        HOME="/home/${CUSER}"
    fi
fi

# 添加判断是否为 /，如果为 / 默认为 /root
if [ $(basename $HOME) == "/" ]; then
    HOME="/root"
fi

DIR_NAME=$(basename $(dirname $(readlink -f $0)))

# 日志会写入 syslog
# 可以通过以下指令查看日志
# tail -f -n 5 /var/log/syslog | grep arcs_setup
log_debug() {
    [[ -L /dev/log || -f /dev/log ]] && logger -p local0.debug -t arcs_setup[$$] $@
    echo "[DEBUG] $@"
}
log_info() {
    [[ -L /dev/log || -f /dev/log ]] && logger -p local0.info -t arcs_setup[$$] $@
    echo "[INFO] $@"
}
log_warning() {
    [[ -L /dev/log || -f /dev/log ]] && logger -p local0.warning -t arcs_setup[$$] $@
    echo "[WARN] $@"
}
log_error() {
    [[ -L /dev/log || -f /dev/log ]] && logger -p local0.err -t arcs_setup[$$] $@
    echo "[ERROR] $@" >&2
}

# 声明ROOT_DIR变量
ROOT_DIR=$(dirname $(readlink -f $0))
INSTALL_DIR=$(dirname $(dirname $0))

# 脚本需要使用 root 用户执行
run_as_root() {
    # ref: https://askubuntu.com/a/30157/8698
    if ! [ $(id -u) = 0 ]; then
        log_info "$0: The script need to be run as root."
        exit 1
    fi
}

# 安装 arcs_update 软件包到系统
copy_files() {
    ## 1. ${ROOT_DIR}获取脚本所在目录
    ## 2. 获取版本号 ${VERSION}
    ## 3. 拷贝目录 /opt/arcs/${VERSION}，版本文件的第一行为软件包整体版本号

    # 判断版本号是否正确，并且不存在
    if [ -d $1/ ]; then
        log_warning "ARCS software updater exsits: $1"
        # return
    else
        mkdir -p $1
    fi
    # chown -R $SUDO_USER ${PREFIX}/

    # 如果已经安装，选择是否覆盖

    # 打印信息
    log_info "ROOT_DIR: ${ROOT_DIR}"

    # 拷贝所有文件到系统目录
    log_info "Copy ${ROOT_DIR}/ to $1"
    cp -av ${ROOT_DIR}/* $1/
}

install_service() {
    log_info "install GeneralWelding oem service..."
    # 取消禁用aubo_scope
    # systemctl disable aubo_scope ||:

    # if [ -f $HOME/.config/autostart/aubo_scope.desktop ]; then
    #     mv $HOME/.config/autostart/aubo_scope.desktop ${ROOT_DIR}/
    # fi
    
    # 配置文件
    INI_DIR="/root/arcs_ws/config"
    INI_FILE="${INI_DIR}/aubo_scope.ini"
    CONTENT="[customization]\nenable_weld=true\nhide_logo=true"
    
    # 修改配置文件
    if [ ! -d "$INI_DIR" ]; then
    	mkdir -p "$INI_DIR"
    fi

    # 检查文件是否存在，不存在则创建
    if [ ! -f "$INI_FILE" ]; then
       touch "$INI_FILE"
    fi

    # 检查tomization和custom_robot_name部分（如果存在）
    sed -i "/^\[customization\]/,/^$/d" "$INI_FILE"
    sed -i "/^\[custom_robot_name\]/,/^$/d" "$INI_FILE"
    if ! grep -q "$CONTENT" "$INI_FILE"; then
       echo -e "$CONTENT" >> "$INI_FILE"
    fi

    # 修改aubo_control文件内容
    # 去除以前的整体替换，使用追加的方式增加extensions模块
    # [ -f /root/arcs_ws/config/aubo_control.conf.old ] || cp -av /root/arcs_ws/config/aubo_control.conf /root/arcs_ws/config/aubo_control.conf.old
    # cp -av ${ROOT_DIR}/aubo_control.conf /root/arcs_ws/config/

    # 执行脚本逻辑
    create_backup
    check_and_append_rocker_module

    # 将rocker服务文件配置到对应位置
    mkdir -p ${INSTALL_DIR}/extensions/rocker
    for filename in ${ROOT_DIR}/rocker-*/*;do
        rm -f ${INSTALL_DIR}/extensions/rocker/$(basename $filename)
    done

    cp -av ${ROOT_DIR}/rocker-*/* ${INSTALL_DIR}/extensions/rocker/

    # 去除旧版本焊接插件，安装新版本
    rm -rf /root/arcs_ws/extensions/weld/
    mkdir /root/arcs_ws/extensions/weld/
    cp -av ${ROOT_DIR}/weld-*/* /root/arcs_ws/extensions/weld/
}

uninstall_service() {
    log_info "uninstall GeneralWelding oem service..."
    # if [ -f $ROOT_DIR/aubo_scope.desktop ]; then
    #     [ -d $HOME/.config/autostart/ ] || mkdir -p $HOME/.config/autostart/
    #     mv $ROOT_DIR/aubo_scope.desktop $HOME/.config/autostart/aubo_scope.desktop 
    # fi

    # 修改aubo_control内容
    cp -av /root/arcs_ws/config/aubo_control.conf.old /root/arcs_ws/config/aubo_control.conf || log_info "not found aubo_control.conf.old !"

    # 定义配置文件路径
    INI_DIR="/root/arcs_ws/config"
    INI_FILE="${INI_DIR}/aubo_scope.ini"

    # 检查文件是否存在
    if [[ ! -f "$INI_FILE" ]]; then
        echo "Error: Configuration file not found: $INI_FILE"
        exit 1
    fi

    # 删除 [customization] 段以及到下一个段落的内容
    sed -i "/^\[customization\]/,/^\[.*\]/ { /^[^[]/d; /^\[customization\]/d; }" "$INI_FILE"

    # 焊接插件文件夹删除
    rm -rf /root/arcs_ws/extensions/weld/

    echo "[customization] section and its contents up to the next section have been deleted."

}


# 配置文件路径
CONFIG_FILE="/root/arcs_ws/config/aubo_control.conf"

# 备份文件路径
BACKUP_FILE="${CONFIG_FILE}.old"

# 新的[[Extension]] rocker 模块内容
NEW_ROCKER_EXTENSION=$(cat << 'EOF'

[[Extension]]
    location = "extensions/rocker/rocker.so"
    bundle = "rocker"

    # 别名
    alias = "rocker"
    enable = true

    # 配置参数
    [Extension.options]
        device_info = "/dev/ttyRobotTool,115200,N,8,1"
        # Tool的XYZ对应Rocker的XYZ(1,2,3)
        tool_x = 1
        tool_y = -3
        tool_z = 2
        pose_speed_fast = 0.15
        pose_speed_slow = 0.06
        ori_velc = 0.008
        acc = 1.0
        debug = 1
        rotation = 0.0 # 安装方式与末端坐标系的安装旋转角度(浮点数)
EOF
)

# 创建备份文件
create_backup() {
    # 配置文件备份存在时，不创建
    if [ ! -f "$BACKUP_FILE" ]; then
        echo "正在备份配置文件为 $BACKUP_FILE..."
        cp -av "$CONFIG_FILE" "$BACKUP_FILE"
        echo "备份完成。"
    else
        echo "备份文件已存在：$BACKUP_FILE"
    fi
}

# 检查并添加新的[[Extension]] rocker 模块
check_and_append_rocker_module() {
    if grep -qPzo "\[\[Extension\]\][^\[]*alias = \"rocker\"" "$CONFIG_FILE"; then
        echo "文件中已经存在完整的'rocker'模块，未做任何修改。"
    else
        echo "文件中没有找到完整的'rocker'模块，正在追加新的'rocker'模块..."
        echo "$NEW_ROCKER_EXTENSION" >> "$CONFIG_FILE"
        echo "新的'rocker'模块已追加到配置文件末尾。"
    fi
}

case "$1" in
    extract)
        # 参数个数为1则退出
        [ $# -lt 2 ] && exit 2
        copy_files $2/${VERSION}
#        create_desktop_link $2/${VERSION}
    ;;
    reinstall)
        [ $# -ge 2 ] && ROBOT_SERIAL=$2
        run_as_root

        # 如果有 /etc/default/arcs 配置文件
#        if test -f ${CHROOT}/etc/default/arcs; then
#            uninstall_current_version

            # 首先删除配置
#            rm ${CHROOT}/etc/default/arcs
#        fi
        uninstall_service
        install_service
#        create_desktop_link ${PREFIX}/${VERSION}
    ;;
    install)
        [ $# -ge 2 ] && ROBOT_SERIAL=$2
        run_as_root

        # 如果有 /etc/default/arcs 配置文件
#        if test -f ${CHROOT}/etc/default/arcs; then
#            uninstall_current_version
#        fi
        install_service
#        create_desktop_link ${PREFIX}/${VERSION}
    ;;
    uninstall)
        uninstall_service
    ;;
    help)
        log_info "Usage: $0 help|extract|install|reinstall|uninstall"
        ## 环境变量帮助信息
        log_info "Environment variables: CHROOT,ARCH"
        exit 0;
    ;;
    *)
        exit 1
    ;;
esac
